<template>
  <div class="login">
    <img src="../assets/image/logo.png" alt="" width="172" height="44" class="logo">
    <main class="login-main">
      <div class="login-main-content">
        <div class="login-left">
          <h3>让中小企业都有自己的法务部门</h3>
          <img src="../assets/image/login-background.png">
        </div>
        <div class="login-box">
          <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="0" class="login-form">
            <div class="login-title">
              <p>账号密码登录</p>
            </div>
            <el-form-item class="login-form-item" prop="user_name">
              <div class="label">登录账号</div>
              <el-input v-model="ruleForm.user_name" :prefix-icon="Iphone" size="large" placeholder="请输入账号"
                class="input-with-select" :disabled="isLogin" maxlength="11" @keyup.enter="submitForm(ruleFormRef)" />
            </el-form-item>
            <el-form-item class="login-form-item" prop="user_pwd">
              <div class="label">登录密码</div>
              <el-input v-model="ruleForm.user_pwd" :show-password="showPassword" size="large" :prefix-icon="Lock"
                placeholder="请输入密码" class="input-with-select" @keyup.enter="submitForm(ruleFormRef)" />
            </el-form-item>
            <div class="remember">
              <span @click="rememberAccount">记住账户</span>
            </div>
            <el-form-item class="login-btn">
              <el-button class="btn btn-primary" :loading="loginLoading" @click.prevent="submitForm(ruleFormRef)">
                {{ TUITranslateService.t("Login.登录") }}
              </el-button>
            </el-form-item>
          </el-form>
          <div class="tip">
            为保证平台功能正常运行以及您的数据安全，请使<br />用 <a href="https://www.google.cn/chrome/index.html" target="_blank">Chrome</a> 或
            <a href="https://www.microsoft.com/zh-cn/edge/?form=MA13FJ" target="_blank">Edge</a> 等现代浏览器
          </div>
        </div>
      </div>

    </main>
  </div>
</template>
<script lang="ts" setup>
import { TUITranslateService, TUIUserService } from '@tencentcloud/chat-uikit-engine';
import { TUILogin } from '@tencentcloud/tui-core';
import type { FormInstance } from 'element-plus';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
// import Header from '../components/Header.vue';
import { onMounted, ref } from '../TUIKit/adapter-vue';
// import AdvList from '../components/AdvList.vue';
// import AdvListItem from '../components/AdvListItem.vue';
// import { Link, qrList, mobileList } from '../utils/link';
import { loginSystem } from '@/api';
import { useUserStore } from '@/store/user';
import { Iphone, Lock } from '@element-plus/icons-vue';

const userStore = useUserStore()


const props = withDefaults(
  defineProps<{
    language: string;
  }>(),
  {
    language: 'zh',
  },
);
const emits = defineEmits(['changeLanguage']);

const locale = ref<string>(props.language);
const router = useRouter();
const isLogin = ref(false);
const showMini = ref(false);
const ruleFormRef = ref<FormInstance>();
const showPassword = ref(true);
const loginLoading = ref(false);

onMounted(() => {
  const userAccount = localStorage.getItem('TUIKit-userAccount');
  if(userAccount) {
    ruleForm.value.user_name = userAccount;
  }
});
const rememberAccount = () => {
  if (ruleForm.value.user_name) {
    localStorage.setItem('TUIKit-userAccount', ruleForm.value.user_name);
    ElMessage({
      message: '记录成功',
      type: 'success',
    })
  } else {
    ElMessage({
      message: '请先输入手机号',
      type: 'warning',
    })
  }
}

const validateuser_name = (rule: any, value: any, callback: any) => {
  if (!rule.required) {
    callback();
  } else if (!value) {
    callback(new Error('请输入手机号'));
  } else {
    callback();
  }
};

const validateuser_pwd = (rule: any, value: any, callback: any) => {
  if (!rule.required) {
    callback();
  } else if (!value) {
    callback(new Error('请输入密码'));
  } else {
    callback();  
  }
};

const ruleForm = ref({
  user_name: '',
  user_pwd: ''
});

const rules = ref({
  user_name: [{ required: true, validator: validateuser_name, trigger: 'blur' }],
  user_pwd: [{ required: true, validator: validateuser_pwd, trigger: 'blur' }],
});

if (localStorage.getItem('TUIKit-userInfo')) {
  const storgeUserInfo = localStorage.getItem('TUIKit-userInfo') || '';
  const userInfo = JSON.parse(storgeUserInfo);
  if (new Date(userInfo?.expire) > new Date()) {
    isLogin.value = true;
  }
}

 const openDownloadLink = (type: any) => {
  type.download && openFullPlatformLink(type.download);
  !type.download && type.url && openFullPlatformLink(type.url);
};

const openFullPlatformLink = (link: string) => {
  window.open(link);
};

const submitForm = (formEl: any, callback: any) => {
  if (!formEl) return;
  formEl.validate((valid: any, callback: any) => {
    if (valid) {
      loginLoading.value = true;
      loginSystem({
        user_name: ruleForm.value.user_name,
        user_pwd: ruleForm.value.user_pwd,
      }).then((res: any) => {
        let result = res.data;
        localStorage.setItem('token', result.token)
        userStore.updateUserInfo(result.user_info)
        localStorage.setItem('sign', result.sign)
        router.push({ path: '/home' });
      }).catch((err: any) => {
        loginLoading.value = false;
      })
    } else {
      return false;
    }
  });
};

const login = (loginInfo: any) => {
  TUILogin.login(loginInfo)
    .then((res: any) => {
      router.push({ path: 'home' });
      TUIUserService.switchUserStatus({ displayOnlineStatus: true });
    })
    .catch((error: any) => {
      ElMessage({
        message: TUITranslateService.t('登录失败'),
        grouping: true,
        type: 'error',
      });
    });
};

const exitLogin = async () => {
  localStorage.removeItem('TUIKit-userInfo');
  isLogin.value = false;
};

const handleJump = (item: any) => {
  switch (item.type) {
    case 'android':
      openFullPlatformLink(item.url);
      break;
    case 'iphone':
      openFullPlatformLink(item.url);
      break;
    case 'miniprogram':
      showMini.value = true;
      break;
  }
};

function changeLanguage(language: string) {
  emits('changeLanguage', language);
}
</script>

<style scoped lang="scss">
@import "../styles/login.scss";

.login-from-item {
  margin-top: 20px;
}

.login-btn {
  margin-top: 20px !important;
}
</style>
